import React, {useEffect, useState} from "react";
import {Button, Col, DatePicker, Form, Input, InputNumber, message, Modal, Row, Select} from "antd";
import type {Result} from "@/types/result";
import salaryApi from "@/api/salaryApi.ts";
import {Salary} from "@/types/resp/salary";
import EmployeeSelector from "@/pages/employee/EmployeeSelector.tsx";

interface SalaryAddProps {
  visible: boolean;
  id: number;
  onCloseSalaryAdd: () => void;
}

const SalaryAdd: React.FC<SalaryAddProps> = ({visible, id, onCloseSalaryAdd}) => {

  const [form] = Form.useForm<Salary>();
  const [messageApi, messageContextHolder] = message.useMessage();

  const rules = {
    employeeName: [
      { required: true, message: '请输入员工姓名' }
    ],
    basicSalary: [
      { required: true, message: '请输入基本工资' }
    ],
    socialSecurityDeduction: [
      { required: true, message: '请输入社保扣除' }
    ],
    housingFundDeduction: [
      { required: true, message: '请输入公积金扣除' }
    ],
    personalIncomeTaxDeduction: [
      { required: true, message: '请输入个人所得税扣除' }
    ],
    otherDeductions: [
      { required: true, message: '请输入其他扣除' }
    ],
    grossSalary: [
      { required: true, message: '请输入应发工资' }
    ],
    netSalary: [
      { required: true, message: '请输入实发工资' }
    ],
    payDate: [
      { required: true, message: '请输入发放日期' }
    ],
  };

  let salaryForm: Partial<Salary> = {}

  const [title, setTitle] = useState('新增员工薪资');

  useEffect(() => {
    if (!visible) {
      return
    }
    if (id) {
      setTitle('编辑员工薪资')
      initSalaryFormById(id)
    } else {
      setTitle('新增员工薪资')
      form.resetFields();
    }
  }, [visible]);

  const initSalaryFormById = async (id: number) => {
    const resp: Result<Salary> = await salaryApi.findById(id)
    if (resp && resp.code === 1 && resp.data) {
      salaryForm = resp.data
      form.setFieldsValue(resp.data);
    }
  }

  const onSave = async () => {
    try {
      await form.validateFields()

      let salary2Save:Salary = form.getFieldsValue()
      if (id) {
        salary2Save = Object.assign(salaryForm, salary2Save)
      }
      const resp: Result<void> = await salaryApi.save(salary2Save);
      if (!resp || resp.code !== 1) {
        messageApi.error('保存失败:' + (resp.msg ? resp.msg : '未知异常'));
        return
      }
      messageApi.success('保存成功');
      onBack()
    } catch (error) {
      console.error('There was an error submitting the form!', error);
    }
  };

  const onReset = () => {
    setTitle('新增员工薪资')
    form.resetFields();
  };
  
  const [employeeSelectorVisible, setEmployeeSelectorVisible] = useState(false);
  const findEmployee = () => {
    setEmployeeSelectorVisible(true);
  }
  const handleEmployeeSelected = (selectedEmployee: { employeeId?: number; employeeName?: string; }) => {
    setEmployeeSelectorVisible(false)
    if (selectedEmployee && 'employeeId' in selectedEmployee) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      employeeId: selectedEmployee['employeeId'],
      employeeName: selectedEmployee['employeeName'],
      }));
    }
  };
  const handleCloseEmployeeSelector = () => {
    setEmployeeSelectorVisible(false)
  };

  const onBack = () => {
    onCloseSalaryAdd()
  };

  const addFooter = (
    <div className='custom-footer'>
      <Button type="primary" onClick={onSave}>保存</Button>
      <Button onClick={onReset} style={{marginLeft: 'var(--button-margin-left)'}}>重置</Button>
      <Button type="primary" onClick={onBack} style={{marginLeft: 'var(--button-margin-left)'}}>关闭</Button>
    </div>
  );

  return (
    <Modal title={title} open={visible} onCancel={onCloseSalaryAdd} width={'var(--modal-width)'}
        footer={addFooter} style={{marginTop: 'var(--modal-margin-top)'}}>
      {messageContextHolder}
      <Form form={form} name="salaryForm" labelCol={{span: 6}}>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="employeeName" label="员工姓名"  rules={rules.employeeName}>
              <Input.Search placeholder="请选择员工姓名" onSearch={findEmployee} readOnly={true} />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="basicSalary" label="基本工资" rules={rules.basicSalary}>
              <InputNumber min={1} max={99999999} precision={2} step={0.1} />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="performanceSalary" label="绩效工资">
              <InputNumber min={1} max={99999999} precision={2} step={0.1} />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="bonus" label="奖金">
              <InputNumber min={1} max={99999999} precision={2} step={0.1} />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="allowance" label="津贴">
              <InputNumber min={1} max={99999999} precision={2} step={0.1} />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="overtimePay" label="加班费">
              <InputNumber min={1} max={99999999} precision={2} step={0.1} />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="socialSecurityDeduction" label="社保扣除" rules={rules.socialSecurityDeduction}>
              <InputNumber min={1} max={99999999} precision={2} step={0.1} />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="housingFundDeduction" label="公积金扣除" rules={rules.housingFundDeduction}>
              <InputNumber min={1} max={99999999} precision={2} step={0.1} />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="personalIncomeTaxDeduction" label="个人所得税扣除" rules={rules.personalIncomeTaxDeduction}>
              <InputNumber min={1} max={99999999} precision={2} step={0.1} />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="otherDeductions" label="其他扣除" rules={rules.otherDeductions}>
              <InputNumber min={1} max={99999999} precision={2} step={0.1} />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="grossSalary" label="应发工资" rules={rules.grossSalary}>
              <InputNumber min={1} max={99999999} precision={2} step={0.1} />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="netSalary" label="实发工资" rules={rules.netSalary}>
              <InputNumber min={1} max={99999999} precision={2} step={0.1} />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="payDate" label="发放日期" rules={rules.payDate}>
              <DatePicker/>
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="paymentMethod" label="支付方式">
              <Select placeholder="请选择支付方式" options={[
                { value: 10, label: <span>银行转账</span> },
                { value: 20, label: <span>现金</span> },
                { value: 30, label: <span>支票</span> }
              ]} />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="bankAccountNumber" label="银行账号">
              <Input maxLength={64} placeholder="请输入银行账号"/>
            </Form.Item>
          </Col>
        </Row>
      </Form>
      <EmployeeSelector visible={employeeSelectorVisible} onEmployeeSelected={handleEmployeeSelected} onCloseEmployeeSelector={handleCloseEmployeeSelector} />
    </Modal>
  )
}

export default SalaryAdd;
